package cpm.itwn.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import cpm.itwn.springcloud.service.PaymentService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {



    @Override
    public String paymentInfo_OK(Integer id) {
        return "线程池" + Thread.currentThread().getName() +" paymentInfo_OK : id "+id +"\t"+"O(∩_∩)O哈哈~";
    }

    /**
     * 模拟报错环境   1.超时兜底  2.计算异常兜底
     *
     *  方案一:
     *      1.主启动类添加激活@EnableCircuitBreaker
     *
     *      2.方法上添加@HystrixCommand
     *      paymentInfo_TimeOut     TimeUnit.SECONDS.sleep(5)设置反应时间5秒
     *
     *      fallbackMethod      失败后的,兜底方法
     *      HystrixProperty     线程超时时间  value=3  要求时间3秒
     *
     * @param id
     * @return
     */

    @Override
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
    })
    public String paymentInfo_TimeOut( Integer id) {
        //int num=10/0;       //报错兜底
        try {
             TimeUnit.SECONDS.sleep(2);     //超时兜底
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池" + Thread.currentThread().getName() +" paymentInfo_TimeOut : id "+id +"\t"+"O(∩_∩)O哈哈~";
    }

    public String paymentInfo_TimeOutHandler(Integer id){
        return "线程池" + Thread.currentThread().getName() +" paymentInfo_TimeOutHandler系统忙,请稍后重试! : id "+id +"\t"+"o(╥﹏╥)o";
    }


    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback" ,commandProperties ={
            @HystrixProperty(name="circuitBreaker.enabled" ,value="true"),      //是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="10"),   //请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds" ,value="10000"),   // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到60%后跳闸,也就是6次

    })
    public String paymentCircuitBreaker(Integer id){
        if(id <0){
            throw new RuntimeException(" **** id 不能为负数 ****");
        }
        String s = IdUtil.simpleUUID();     //生成一个唯一订单号

        return Thread.currentThread().getName()+"\t"+"调用成功 流水号:"+s;
    }

    public String paymentCircuitBreaker_fallback(Integer id){
        return "id 不能为负数 ,请稍后再试! /(ㄒoㄒ)/~~  id+"+id;
    }




}
